package com.lge.pitchingcoins.ui.server.layer;

import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lge.pitchingcoins.R;
import com.lge.pitchingcoins.ui.server.ClientScore;
import com.lge.pitchingcoins.ui.server.ServerMainActivityWithCocos;
import com.lge.pitchingcoins.util.PitchingCoinsLog;
import com.lge.pitchingcoins.util.databases.PitchingCoinsDatabaseHandler;

import org.cocos2d.actions.base.CCRepeatForever;
import org.cocos2d.actions.interval.CCIntervalAction;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.actions.interval.CCTintBy;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCMultiplexLayer;
import org.cocos2d.menus.CCMenu;
import org.cocos2d.menus.CCMenuItemFont;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.types.ccColor3B;

import java.util.ArrayList;

public class ServerMainLayer extends CCLayer {
    public static final int REMOVE_HIGHSCORE_LISTVIEW = 1000;
    public static final int DISPLAY_HIGHSCORE_LISTVIEW = 1001;
    public static final int HIGHSCORE_NOTIFY_DATA_CHANGED = 1002;
    
    private Context mContext = null;
    
    private ListView highscoreListView = null;
    private HighscoreListAdapter highscoreListAdapter = null;
    
    private TextView gradeTextView = null;
    private TextView nickNameTextView = null;
    private TextView scoreTextView = null;
    
    private ArrayList<ClientScore> clientScoreArrayList = null;
    
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REMOVE_HIGHSCORE_LISTVIEW) {
                highscoreListView.setVisibility(View.GONE);
            } else if (msg.what == DISPLAY_HIGHSCORE_LISTVIEW) {
                highscoreListView.setVisibility(View.VISIBLE);
            } else if (msg.what == HIGHSCORE_NOTIFY_DATA_CHANGED) {
                highscoreListAdapter.notifyDataSetChanged();
            }
        }
    };
    

    public ServerMainLayer(Context context) {
        super();

        mContext = context;
        this.setIsKeyEnabled(true);
        
        initComponent();
    }
    
    // Callback Methods
    @Override
    public boolean ccKeyDown(int keyCode, KeyEvent event) {
        return super.ccKeyDown(keyCode, event);
    }

    public void gameConnectButtonPressed(Object sender) {
        ConnectivityManager connectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfoForWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (networkInfoForWifi.isConnected()) {
            mHandler.sendEmptyMessage(REMOVE_HIGHSCORE_LISTVIEW);
            
            ((CCMultiplexLayer)getParent()).setTag(1);
            ((CCMultiplexLayer)getParent()).switchTo(1);
        } else {
            ((ServerMainActivityWithCocos)mContext).getHandler().sendEmptyMessage(ServerMainActivityWithCocos.MAKE_TOAST);
        }
    }
    
    @Override
    public void onEnter() {
        super.onEnter();
        
        mHandler.sendEmptyMessage(DISPLAY_HIGHSCORE_LISTVIEW);
        mHandler.sendEmptyMessage(HIGHSCORE_NOTIFY_DATA_CHANGED);
    }

    @Override
    public void onExit() {
        super.onExit();
       
    }

    
    // Member Methods
    public void initComponent() {
        clientScoreArrayList = new ArrayList<ClientScore>();
        
        getDataFromDB();
        
        highscoreListView = new ListView(mContext);
        highscoreListAdapter = new HighscoreListAdapter(mContext);
        highscoreListView.setAdapter(highscoreListAdapter);
        highscoreListView.setBackgroundResource(R.color.white);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int)getContentSize().width * 2 / 3, (int)getContentSize().height * 3 / 8, Gravity.CENTER);
        CCDirector.sharedDirector().getActivity().addContentView(highscoreListView, layoutParams);
        
        if (clientScoreArrayList.size() == 0) {
            mHandler.sendEmptyMessage(REMOVE_HIGHSCORE_LISTVIEW);
        }
        
        
        CCMenuItemFont.setFontSize(100);
        CCMenuItemFont.setFontName("DroidSans");

        CCMenuItemFont gameConnectButton = CCMenuItemFont.item(mContext.getString(R.string.gameConnectButtonText), this, "gameConnectButtonPressed");

        CCIntervalAction colorAction = CCTintBy.action(0.5f, ccColor3B.ccc3(0, -255, -255));
        CCIntervalAction colorBack = colorAction.reverse();
        CCIntervalAction sequence = CCSequence.actions(colorAction, colorBack);
        gameConnectButton.runAction(CCRepeatForever.action(sequence));

        CCMenu menu = CCMenu.menu(gameConnectButton);
        menu.setPosition(getContentSize().width / 2, getContentSize().height * 4 / 5);
        menu.alignItemsVertically();

        addChild(menu);
    }
    
    public void getDataFromDB() {
        PitchingCoinsDatabaseHandler databaseHandler = new PitchingCoinsDatabaseHandler(mContext);

        databaseHandler.openDatabase();

        Cursor cursor = databaseHandler.fetchAllScore();
        cursor.moveToFirst();
        
        while (cursor.moveToNext()) {
            String nickname = cursor.getString(0);
            int score = cursor.getInt(1);
            
            PitchingCoinsLog.d("Name : " + nickname + ", Score : " + score);
            clientScoreArrayList.add(new ClientScore(nickname, score));
        }

        databaseHandler.closeDatabase();
    }

    
    // Inner Classes
    class HighscoreListAdapter extends BaseAdapter {
        private Context mContext = null;
        
        public HighscoreListAdapter(Context context) {
            super();

            this.mContext = context;
        }

        @Override
        public int getCount() {
            if (clientScoreArrayList.size() > 5) {
                return 5;
            } else {
                return clientScoreArrayList.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            View row = view;

            if (row == null) {
                row = LayoutInflater.from(mContext).inflate(R.layout.adapter_score_list, null);
            }

            gradeTextView = (TextView)row.findViewById(R.id.gradeTextView);
            nickNameTextView = (TextView)row.findViewById(R.id.nickNameTextView);
            scoreTextView = (TextView)row.findViewById(R.id.scoreTextView);

            gradeTextView.setText((position + 1) + "");
            nickNameTextView.setText(clientScoreArrayList.get(position).getNickname().substring(0, clientScoreArrayList.get(position).getNickname().length() - 7));
            scoreTextView.setText(clientScoreArrayList.get(position).getScore() + "");

            return row;
        }
    }
}